/*
* Copyright (c) 2017 . All Rights Reserved.
*/
package com.cgmnx.admin.web.controller;

import com.cgmnx.admin.biz.rbac.ResourceBiz;
import com.cgmnx.admin.common.bean.UserContext;
import com.cgmnx.admin.common.util.JacksonMapper;
import com.cgmnx.admin.dao.entity.rbac.ResourceEntity;
import com.cgmnx.admin.web.converter.vm.MenuVmConverter;
import com.cgmnx.admin.web.model.vm.MenuTreeVm;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author: created  Date: 17/1/2 Time: 下午1:28
 * @version: 1.0
 */
@Controller
public abstract class BaseAdminController {

    @Autowired
    private ResourceBiz resourceBiz;

    @Autowired
    private MenuVmConverter menuVmConverter;

    public void setLoginUser(ModelAndView modelAndView) {
        if (UserContext.getUserInfo() != null) {
            modelAndView.addObject("userInfo", JacksonMapper.encodeQuietly(UserContext.getUserInfo()));
        } else {
            modelAndView.addObject("userInfo", "{}");
        }
    }

    public void setMenuList(ModelAndView modelAndView) {
        if (UserContext.getUserInfo() != null) {
            modelAndView.addObject("menuList", JacksonMapper.encodeQuietly(queryMenuList(UserContext.getUserInfo().getUserId())));
        } else {
            modelAndView.addObject("menuList", JacksonMapper.encodeQuietly(Lists.<MenuTreeVm>newArrayList()));
        }
    }


    public List<MenuTreeVm> queryMenuList(String userId) {

        if (StringUtils.isBlank(userId)) {
            return Lists.newArrayList();
        }

        List<ResourceEntity> resourceEntityList = resourceBiz.queryByUserId(userId);

        if (CollectionUtils.isEmpty(resourceEntityList)) {
            return Lists.newArrayList();
        }
        return menuVmConverter.entities2Tree(resourceEntityList);
    }


    public void download(HttpServletResponse response, String fileName) {

        File file = new File(fileName);
        if (!file.exists()) {
            return;
        }

        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
        try {
            Files.copy(file, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                IOUtils.closeQuietly(response.getOutputStream());
            } catch (IOException e) {

            }
        }

    }
}